package com.example.demo.service.serviceimpl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.service.TokenService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    RedisTemplate<String,String> redisTemplate;

    /**
     * 根据用户名创建token
     * @param uaccount 账户
     * @return String：token
     */
    @Override
    public String createToken(String uname) {
        String token= JWT.create().withAudience(uname).sign(Algorithm.HMAC256(uname));
        redisTemplate.opsForValue().set(uname,token,60*6, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public boolean isToken(String uname, String token) {
        return redisTemplate.opsForValue().get(uname).equals(token);
    }

    @Override
    public boolean clearToken(String uname) {
        if(redisTemplate.delete(uname)){
            return true;
        }else {
            return false;
        }
    }
}
